package com.bawei.module_live.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.OptIn
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.ExoPlayer
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_live.databinding.ItemLiveBinding // 自动生成的 Item 绑定类
import com.bawei.module_live.data.LiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@OptIn(UnstableApi::class)
class LiveAdapter(
    private val context: Context,
    private val lifecycleScope: CoroutineScope
) : RecyclerView.Adapter<LiveAdapter.LiveViewHolder>() {

    private val liveDataList = mutableListOf<LiveData>()
    val playerManager = PlayerManager(context)
    private var currentPlayingPosition = RecyclerView.NO_POSITION
    private var isResumeMode = false
    
    // 播放状态监听器
    private var onPlayerStateChangeListener: ((position: Int, isPlaying: Boolean) -> Unit)? = null
    
    // 点击进入直播间监听器
    private var onEnterLiveRoomListener: ((liveData: LiveData, position: Int) -> Unit)? = null

    // 播放器管理器（优化资源复用）
    inner class PlayerManager(private val context: Context) {
        internal val players = mutableMapOf<Int, ExoPlayer>()
        private val maxCachedPlayers = 3 // 减少缓存数量，避免卡顿

        fun getOrCreatePlayer(position: Int, mediaUri: String): ExoPlayer {
            val player = players[position]
            if (player == null) {
                val newPlayer = createPlayer(mediaUri)
                players[position] = newPlayer
                if (players.size > maxCachedPlayers) {
                    releaseFarthestPlayer(position)
                }
                return newPlayer
            } else {
                // 如果 mediaItem 不同，重新设置
                val currentUri = (player.currentMediaItem?.localConfiguration?.uri?.toString() ?: "")
                if (currentUri != mediaUri && mediaUri.isNotEmpty()) {
                    player.setMediaItem(MediaItem.fromUri(mediaUri))
                    // 只在当前播放项时 prepare，避免频繁 prepare 导致卡顿
                    if (position == currentPlayingPosition) {
                        player.prepare()
                    }
                }
                return player
            }
        }

        private fun createPlayer(mediaUri: String): ExoPlayer {
            return ExoPlayer.Builder(context)
                .setLoadControl(
                    DefaultLoadControl.Builder()
                        .setBufferDurationsMs(
                            5_000,  // 最小缓冲
                            20_000, // 最大缓冲
                            1_000,  // 播放前缓冲
                            3_000   // 暂停后缓冲
                        )
                        .build()
                )
                .build()
                .apply {
                    setMediaItem(MediaItem.fromUri(mediaUri))
                    repeatMode = Player.REPEAT_MODE_ALL
                    playWhenReady = false
                    volume = 0f // 静音兜底
                }
        }

        private fun releaseFarthestPlayer(currentPosition: Int) {
            val farthestPos = players.keys
                .maxByOrNull { kotlin.math.abs(it - currentPosition) }
            farthestPos?.let { releasePlayer(it) }
        }

        fun releasePlayer(position: Int) {
            players[position]?.release()
            players.remove(position)
        }

        fun releaseAll() {
            players.values.forEach { it.release() }
            players.clear()
        }
        
        fun pauseAllPlayers() {
            players.values.forEach { player ->
                player.playWhenReady = false
            }
        }
        
        fun pauseOtherPlayers(exceptPosition: Int) {
            players.forEach { (position, player) ->
                if (position != exceptPosition) {
                    player.playWhenReady = false
                }
            }
        }
    }

    // ViewHolder（基于 ViewBinding）
    inner class LiveViewHolder(private val binding: ItemLiveBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(liveData: LiveData, position: Int) {
            // 绑定标题、描述
            binding.liveTitle.text = liveData.name
            binding.liveDesc.text = liveData.description

            // 初始化播放器
            val player = playerManager.getOrCreatePlayer(position, liveData.videopath)
            binding.playerView.player = player

            // 只让当前播放项自动播放
            if (position == currentPlayingPosition) {
                player.playWhenReady = true
                player.prepare()
            } else {
                player.playWhenReady = false
            }

            // 设置点击进入直播间监听
            binding.goLive.setOnClickListener {
                onEnterLiveRoomListener?.invoke(liveData, position)
            }

            // 预加载相邻项（优化播放流畅度）
            preloadAdjacent(position)
        }

        private fun preloadAdjacent(position: Int) {
            if (position + 1 < itemCount) {
                lifecycleScope.launch(Dispatchers.Main) {
                    val nextData = liveDataList[position + 1]
                    playerManager.getOrCreatePlayer(position + 1, nextData.videopath)
                }
            }
            if (position - 1 >= 0) {
                lifecycleScope.launch(Dispatchers.Main) {
                    val prevData = liveDataList[position - 1]
                    playerManager.getOrCreatePlayer(position - 1, prevData.videopath)
                }
            }
        }

        fun detachPlayer() {
            binding.playerView.player = null
        }
    }

    // Adapter 核心方法
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LiveViewHolder {
        val binding = ItemLiveBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return LiveViewHolder(binding)
    }

    override fun onBindViewHolder(holder: LiveViewHolder, position: Int) {
        val liveData = liveDataList[position]
        holder.bind(liveData, position)

        // 动态控制include显示
        val includeFlagAd = holder.itemView.findViewById<android.view.View>(com.bawei.module_live.R.id.include_flag_ad)
        val includeLiveEven = holder.itemView.findViewById<android.view.View>(com.bawei.module_live.R.id.include_live_even)
        includeFlagAd?.visibility = android.view.View.GONE
        includeLiveEven?.visibility = android.view.View.GONE

        if ((position + 1) % 2 == 1) {
            // 奇数，显示广告样式
            includeFlagAd?.visibility = android.view.View.VISIBLE
            // 广告卡片根布局
            val flagAdRoot = includeFlagAd?.findViewById<android.view.View>(com.bawei.module_live.R.id.include_flag_ad)
            // 保证每次onBind都显示
            flagAdRoot?.visibility = android.view.View.VISIBLE
            // 设置X按钮点击事件
            val closeBtn = includeFlagAd?.findViewById<android.widget.ImageView>(com.bawei.module_live.R.id.ad_flag_close)
            closeBtn?.setOnClickListener {
                flagAdRoot?.visibility = android.view.View.GONE
            }
        } else {
            // 偶数，显示图文样式
            includeLiveEven?.visibility = android.view.View.VISIBLE
            // 设置本地图片
            val img = includeLiveEven?.findViewById<android.widget.ImageView>(com.bawei.module_live.R.id.avatar)
            img?.setImageResource(com.bawei.module_live.R.drawable.ic_shop)
            // 设置“了解更多”按钮点击事件
            val btn = includeLiveEven?.findViewById<android.widget.Button>(com.bawei.module_live.R.id.btn)
            btn?.setOnClickListener {
                // 这里可以实现跳转或弹窗逻辑
                // 例如：Toast.makeText(context, "了解更多", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onViewAttachedToWindow(holder: LiveViewHolder) {
        super.onViewAttachedToWindow(holder)
        val position = holder.bindingAdapterPosition
        if (position != RecyclerView.NO_POSITION) {
            holder.bind(liveDataList[position], position)
        }
    }

    override fun onViewDetachedFromWindow(holder: LiveViewHolder) {
        super.onViewDetachedFromWindow(holder)
        val position = holder.bindingAdapterPosition
        pauseVideo(position) // 只暂停，不刷新
        holder.detachPlayer()
    }

    override fun getItemCount(): Int = liveDataList.size

    // 数据更新
    fun setData(data: List<LiveData>) {
        liveDataList.clear()
        liveDataList.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data: List<LiveData>) {
        val startPos = liveDataList.size
        liveDataList.addAll(data)
        notifyItemRangeInserted(startPos, data.size)
    }

    // 播放控制
    fun setCurrentPlayingPosition(position: Int) {
        if (position == currentPlayingPosition) return

        // 暂停之前的播放项
        if (currentPlayingPosition != RecyclerView.NO_POSITION) {
            val prevPlayer = playerManager.getOrCreatePlayer(currentPlayingPosition, liveDataList.getOrNull(currentPlayingPosition)?.videopath ?: "")
            prevPlayer.playWhenReady = false
        }

        currentPlayingPosition = position
        if (position in 0 until itemCount) {
            val player = playerManager.getOrCreatePlayer(position, liveDataList[position].videopath)
            player.playWhenReady = isResumeMode
            // 只在设置当前播放位置时 prepare
            player.prepare()
        }
    }

    fun setResumeMode(resume: Boolean) {
        isResumeMode = resume
        if (currentPlayingPosition != RecyclerView.NO_POSITION) {
            val player = playerManager.getOrCreatePlayer(currentPlayingPosition, liveDataList.getOrNull(currentPlayingPosition)?.videopath ?: "")
            player.playWhenReady = resume
        }
    }

    fun clearData() {
        liveDataList.clear()
        notifyDataSetChanged()
    }

    fun playVideo(position: Int) {
        val old = currentPlayingPosition
        setCurrentPlayingPosition(position)
        setResumeMode(true)
        if (old != RecyclerView.NO_POSITION) notifyItemChanged(old)
        notifyItemChanged(position)
    }

    fun pauseVideo(position: Int) {
        if (position in 0 until itemCount) {
            val player = playerManager.getOrCreatePlayer(position, liveDataList[position].videopath)
            player.playWhenReady = false
            // notifyItemChanged(position) // 这一行删掉！
        }
    }

    // 新增方法：设置播放状态监听器
    fun setOnPlayerStateChangeListener(listener: (position: Int, isPlaying: Boolean) -> Unit) {
        onPlayerStateChangeListener = listener
    }
    
    // 新增方法：设置进入直播间监听器
    fun setOnEnterLiveRoomListener(listener: (liveData: LiveData, position: Int) -> Unit) {
        onEnterLiveRoomListener = listener
    }
    
    // 新增方法：暂停所有播放器
    fun pauseAllPlayers() {
        playerManager.pauseAllPlayers()
    }
    
    // 新增方法：暂停其他播放器
    fun pauseOtherPlayers(exceptPosition: Int) {
        playerManager.pauseOtherPlayers(exceptPosition)
    }

    // 静音所有播放器，兜底方案
    fun muteAllPlayers() {
        playerManager.players.values.forEach { player ->
            player.volume = 0f
        }
    }

    // 资源释放
    fun releaseAllPlayers() {
        // 解绑所有PlayerView，防止声音残留
        // 遍历所有可见ViewHolder并解绑
        notifyDataSetChanged() // 触发onViewDetachedFromWindow，自动解绑
        playerManager.releaseAll()
    }

    // 加载更多 Footer（可选扩展）
    fun showLoadingFooter() {
        // 若需加载更多，可添加 Footer 逻辑
    }

    fun hideLoadingFooter() {
        // 隐藏 Footer
    }


}